package _aliyun.elasticsearch.test.document;

import _aliyun.elasticsearch.test.base.ESBase;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huangya
 * @date 2023/1/18
 */
public class IndexApi {

    public static void main(String[] args) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("user", "kimchy");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "trying out Elasticsearch");
        IndexResponse indexResponse = createIndex(jsonMap);
        System.out.println(JSON.toJSONString(indexResponse));
    }

    public static IndexResponse createIndex(Map<String, Object> jsonMap){
        // RestHighLevelClient实例通过REST low-level client builder进行构造。
        RestHighLevelClient client= new RestHighLevelClient(ESBase.getRestClientBuilder());

        IndexRequest indexRequest = new IndexRequest("api_test1").id("1").source(jsonMap);

        /***** 三、Synchronous execution *****/
        IndexResponse indexResponse = null;
        try {
            indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (ElasticsearchStatusException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return indexResponse;
    }
}
